package com.damage.supplier.web;

import com.damage.common.config.CodeConfig;
import com.damage.common.entity.Order;
import com.damage.common.object.BaseResp;
import com.damage.common.service.IPublicService;
import com.damage.common.util.UserUtil;
import com.damage.supplier.oa.sendOrder.ConfirmOrderService;
import com.damage.supplier.service.IReceiveOrderService;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@ResponseBody
@RequestMapping("/order")
@Slf4j
public class ReceiveOrderController {

    @Autowired
    private ConfirmOrderService confirmOrderService;

    @Autowired
    private IPublicService publicService;

    @Autowired
    private IReceiveOrderService receiveOrderService;

    @PostMapping("/confirm/{id}")
    public BaseResp confirmOrder(@PathVariable("id")String taskId,
                                 @RequestParam(value = "isCancel",required = true) Boolean isCancel,
                                 @RequestParam(value = "comment",required = false) String comment){
        try {
            if (isCancel == true){
                if (Strings.isNullOrEmpty(comment)){
                    return BaseResp.error("取消订单需要说明原因！");
                }
            }
            Order order = confirmOrderService.confirmOrCancelOrder(taskId, isCancel,comment);
            if (order == null){
                return BaseResp.error("确认或取消订单失败！");
            }
            return BaseResp.ok(order);
        } catch (Exception e) {
            log.error("完成任务失败，任务taskId:{}",taskId);
            e.printStackTrace();
            return BaseResp.error(e.getMessage());
        }
    }

    @PostMapping("/deliver/{id}")
    public BaseResp deliverOrder(@PathVariable("id")Integer orderId,
                                       HttpSession session){
        User user = UserUtil.getUserFromSession(session);
        if (user == null || Strings.isNullOrEmpty(user.getId())){
            //用户未登录
            return BaseResp.error(CodeConfig.ERROR_NOT_LOGIN);
        }

        Order order = publicService.findOrderById(orderId);
        //验证身份
        if (!user.getFirstName().equals(order.getOrderReceiver())){
            return BaseResp.error("订单的接收人不是当前用户，不能完成订单！");
        }

        Integer result = receiveOrderService.deliverOrder(orderId);

        if (result == 0){
            //操作失败
            return BaseResp.error("将订单置为已发货状态的操作失败！");
        }
        return BaseResp.ok();

    }
}
